# -*- coding: utf-8 -*-#
#-------------------------------------------------------------------------------
# 建立者:       王景渊  
# Name:         1421
# Description:
# Author:       dell
# Date:         2019/4/17
#-------------------------------------------------------------------------------
import json
data = {
    'name':'Bill',
    'company':'Microsoft',
    'age':'34'
}
# 字典转换为json字符串 用dumps
jsonstr = json.dumps(data)
print(type(jsonstr))
print(jsonstr)
print('----------------')


#将json字符串转换为字典用loads
data = json.loads(jsonstr)
print(type(data))
print(data)

json_obj = {
    "name": "zhangsan",
    "age": "23",
    "addr": {
        "province": 'Hunan',
        "city":'Zhuzhou'# 自己建立的json字符串必须使用双引号将键值对括起来，单引号会报错
    }
}

s = """
{
    'name':'Bill',
    'company':'Microsoft',
    'age':34
}
"""
# 使用eval函数将json字符串转换为字典
data = eval(s)
print(type(data))
print(data)

print(data['company'])

# 读取json格式的文件，转换为字典
f = open('files/products.json','r',encoding='utf-8')
jsonstr = f.read()
json1 = eval(jsonstr)
json2 = json.loads(jsonstr)
print(json1)
print(json2)
print(json2[0]['name'])
f.close()

